package se.webbzon.oschi01.action;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;

import se.webbzon.oschi01.command.Command;
import se.webbzon.oschi01.command.UndoableClipboard;
import se.webbzon.oschi01.gui.ApplicationIconSheet;
import se.webbzon.oschi01.gui.ApplicationIcon;
import se.webbzon.oschi01.gui.NBTTransferable;
import se.webbzon.oschi01.nbt.Tag;
import se.webbzon.oschi01.singleton.Singletons;

public class NBTCopyAction extends DefaultAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3220708452920602500L;

	private static final ApplicationIconSheet iconSheet = Singletons.instance(ApplicationIconSheet.class);
	
	private final Tag<?> nbtTag;
	private final UndoableClipboard clipboard;
	
	public NBTCopyAction(Tag<?> nbtTag, UndoableClipboard clipboard) {
		this.nbtTag = nbtTag;
		this.clipboard = clipboard;
		putValue(NAME, "Copy");
		putValue(SMALL_ICON, iconSheet.getIcon(ApplicationIcon.Copy));	
	}
	
	@Override public void actionPerformed(ActionEvent e) {
		performCommand(new CommandImpl());
	}
	
	private final class CommandImpl implements Command, ClipboardOwner {
		
		private ClipboardOwner lastOwner;
		private Transferable lastTransferable;

		@Override public String getName() {
			return "copy " + nbtTag;
		}

		@Override public void redo() {
			lastOwner = clipboard.getOwner();
			lastTransferable = clipboard.getContents(null);
			clipboard.setContents(new NBTTransferable(nbtTag), this);
		}

		@Override public void undo() {
			clipboard.setContents(lastTransferable, lastOwner);
		}

		@Override public void lostOwnership(Clipboard clipboard, Transferable contents) {
			// Do nothing
		}
		
	}

}
